package logic

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"time"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"
	"laundry-service/entity"

	"github.com/zeromicro/go-zero/core/logx"
)

type WxRefundCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	req    *http.Request
}

func NewWxRefundCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext, req *http.Request) *WxRefundCallbackLogic {
	return &WxRefundCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		req:    req,
	}
}

func (l *WxRefundCallbackLogic) WxRefundCallback() (resp *types.Reply, err error) {
	body, err := io.ReadAll(l.req.Body)
	if err != nil {
		return nil, err
	}

	b, s := DecodeNotify(body, l.svcCtx.Config.WxPay.Apiv3Key)
	if !b {
		return nil, errors.New("验签错误")
	}

	orderNumber := s["out_trade_no"]

	order, err := l.svcCtx.Db.GetOrderByNumber(orderNumber)
	if err != nil {
		return nil, err
	}

	if order.State == -1 {
		order.State = -3
		order.PayState = -3
		// 查询退款订单
		refundOrder, err := l.svcCtx.Db.GetOrderRefundByNo(orderNumber)
		if err != nil {
			return nil, err
		}
		attr, _ := json.Marshal(s)
		refundOrder.Attr = string(attr)
		refundOrder.Status = s["refund_status"]
		refundOrder.TransactionId = s["transaction_id"]
		refundOrder.RefundId = s["refund_id"]
		refundOrder.UserReceivedAccount = s["user_received_account"]

		if s["refund_status"] != "REFUND.SUCCESS" {
			successTime, parseErr := time.Parse(time.RFC3339, s["success_time"])
			if parseErr != nil {
				return nil, parseErr
			}
			refundOrder.SuccessTime = successTime
		}

		orderLog := new(entity.OrderLog)
		orderLog.OperatorId = order.UserId
		orderLog.OperatorName = ""
		orderLog.State = -3
		orderLog.OrderId = order.ID
		orderLog.Remark = "退款成功"
		orderLog.OperatorType = 1

		err = l.svcCtx.Db.TxWXRefundNotify(order, refundOrder, orderLog)
		if err != nil {
			return nil, err
		}
	}
	return
}
